//
//  CountdownViewController.m
//  iEasyTime
//
//  Created by User on 7/2/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CountdownViewController.h"


@implementation CountdownViewController

@synthesize mins;
@synthesize secs;
@synthesize countdown;

-(void)viewDidLoad{
	
	startTime = 0;
	endTime = 0;
	stopReference = 0;
	now = 0;
	elapsedTime = 0;
	remainingTime = 0;
	running = NO;
	[self runCountdown];
}

-(IBAction)reset{
	
	startTime = 0;
	endTime = 0;
	stopReference = 0;
	now = 0;
	elapsedTime = 0;
	remainingTime = 0;
	running = NO;
	[self runCountdown];
}

-(IBAction)pause{
	
	if(running == NO){ 
		double test = (([mins.text doubleValue]*60) + [secs.text doubleValue]);		
		if (test != 0){		
			if(startTime == 0){ 
				startTime = [NSDate timeIntervalSinceReferenceDate];
				endTime  = [NSDate timeIntervalSinceReferenceDate] + test;			
			}else{
				now = [NSDate timeIntervalSinceReferenceDate];
				startTime += (now - stopReference);
				endTime += (now - stopReference);
			}
		timer = [NSTimer scheduledTimerWithTimeInterval:(0.02) target:self selector:@selector(runCountdown) userInfo:nil repeats:YES];
		running = YES;
		}
	}else{
		stopReference = [NSDate timeIntervalSinceReferenceDate];
		[timer invalidate];
		running = NO;
	}
}
		
		
-(void)runCountdown{
	
	now = [NSDate timeIntervalSinceReferenceDate];

	if(running == NO){ remainingTime = 0;}
	else{ 
		elapsedTime = now - startTime;
		remainingTime = endTime - now;
	}
	
	seconds = (int)remainingTime;
	int hundredths = (remainingTime - seconds)*100;	
	NSString *myString = [NSString stringWithFormat:@"%02d:%02d:%02d", seconds/60, seconds%60, hundredths];
	countdown.text = myString;
	
	if(running == YES && remainingTime <= 0){ [self finished]; [self reset]; }
} 

-(IBAction)clear{
	[mins resignFirstResponder];
	[secs resignFirstResponder];
}

-(IBAction)finished {
	
    UIAlertView *alert = [[UIAlertView alloc] 
						  initWithTitle:@"Countdown Finished" 
						  message:@"Your countdown has finished." 
						  delegate:nil 
						  cancelButtonTitle:@"Ok, Thanks." 
						  otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
} 

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
